package com.cta.tcp.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import javax.annotation.PostConstruct;

import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

public class TCPServer {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private int port;
	private NioSocketAcceptor acceptor;

	@Autowired
	private TCPServerHandler tcpServerHandler;

	public TCPServer(String port) throws IOException {
		Assert.hasText(port);
		this.port = Integer.valueOf(port);
	}

	@PostConstruct
	public void initServer() throws IOException {
		acceptor = new NioSocketAcceptor();
		acceptor.setDefaultLocalAddress(new InetSocketAddress(this.port));
		acceptor.getFilterChain().addLast("protocol",
				new ProtocolCodecFilter(new TextLineCodecFactory()));
		acceptor.setHandler(tcpServerHandler);
		acceptor.bind();
		logger.info("server is listenig at port" + this.port);
	}

}
